<script setup>

import {ref, reactive, onMounted} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage  } from 'element-plus'; // 使用 Element Plus 的 message 组件
import axios from 'axios'
import { userStore} from "@/store/index.js";
// pinia 存储对象
const userItemStore = userStore();

const router = useRouter();
const refLoginForm = ref(null); // 创建一个 ref 来引用 el-form
const isButtonDisabled = ref(false);
const codeUrl = ref('');
const loginForm = reactive({
  account: 'abc',
  password: '123456',
  code: '1234',
  key: '',
});

const rules = reactive({
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度必须是4位', trigger: 'blur' }
  ]
});

const userLogin = () => {
  refLoginForm.value.validate(valid => {
    if (valid) { // 表单验证成功

      // 登录请求，获取后台返回的UserVo对象、token、并把token存储到浏览器中
      axios.post('/user/login', loginForm).then(res => {

         if (res.status === 200) {
           // 登录成功
           // 1. 存储用户信息
           localStorage.setItem('user', JSON.stringify(res.data));
           // 2. 存储token
           localStorage.setItem('token', res.headers.authorization);

           // 3、更新pinia中用户登录状态、登录后的用户信息
           userItemStore.updateLoginStatus(true)
           userItemStore.updateUser(res.data)

           ElMessage.success('登录成功');

           // 3. 跳转到首页
           router.push('/');
         } else {
           ElMessage.error("登录失败！");
         }
      }).catch(error=>{
        ElMessage.error("登录失败," + error.response.data);
      })


    } else {
      return false;
    }

    // 前端点击登录按钮幂等处理：避免短时间内重复点击
    isButtonDisabled.value = true
    // 5秒后自动恢复可用
    setTimeout(()=>{
      // 此处代码5秒后执行
      isButtonDisabled.value = false
    },5000)

  })
};

// 访问后台，返回图片验证码
const getCaptcha = () => {
  // axois访问后台，返回图片验证码
  axios.get('/user/code').then(res => {
    codeUrl.value = res.data.base64Img;
    loginForm.key = res.data.key;
  })
};

onMounted(()=>{
  getCaptcha()
})

const activeName = ref('userName')

const refSmsForm = ref(null);

const smsForm = reactive({
  telephone: '16165669252',
  code: '1234'
});

const rulesPhone = reactive({
  telephone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度必须是4位', trigger: 'blur' }
  ]
})

const smsDisabled = ref(false);  //发短信按钮是否可用
const smsText =ref('发送短信验证码');

// 发送验证码
const sendSms = () => {
  // telephone 验证
  refSmsForm.value.validateField('telephone', valid => {
    if (valid) {

      // 点击后设置不可用
      smsDisabled.value = true;

      axios.get(`/user/sendSms/${smsForm.telephone}`).then(res => {
        ElMessage.success('发送成功！')
      }).catch(error=>{
        ElMessage.error("发送短信验证码失败！" + error.response.data);
      }).finally(()=>{
        // 15 秒倒计时
        //按钮文字变成倒计时
        let seconds = 15;
        smsText.value = `${seconds}秒后重新发送`;
        let timer = setInterval(() => {
          seconds--;
          if (seconds > 0) {
            smsText.value = `${seconds}秒后重新发送`;
          } else {
            //修改文字
            smsText.value = "发送短信验证码";
            //按钮可用
            smsDisabled.value = false;
            //清除定时器
            clearInterval(timer);
          }
        }, 1000);

      })


    } else {
      console.log('手机号验证失败！')
      return false;
    }
  })
}

// 短信登录
const smsLogin = () => {
  refSmsForm.value.validate(valid => {
    if (valid) { // 表单验证成功

      // 登录请求，获取后台返回的UserVo对象、token、并把token存储到浏览器中
      axios.post('/user/smsLogin', smsForm).then(res => {

        if (res.status === 200) {
          // 登录成功
          // 1. 存储用户信息
          localStorage.setItem('user', JSON.stringify(res.data));
          // 2. 存储token
          localStorage.setItem('token', res.headers.authorization);

          // 3、更新pinia中用户登录状态、登录后的用户信息
          userItemStore.updateLoginStatus(true)
          userItemStore.updateUser(res.data)

          ElMessage.success('登录成功');

          // 3. 跳转到首页
          router.push('/');
        } else {
          ElMessage.error("登录失败！");
        }
      }).catch(error=>{
        ElMessage.error("登录失败," + error.response.data);
      })
    } else {
      return false;
    }

  })
}

</script>



<template>
  <div class="login-container">

    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="用户名登录" name="userName">

        <el-card class="card">
          <h2 class="title">蜗牛书城用户登录</h2>
          <el-form ref="refLoginForm" :model="loginForm"
                   class="login-form"
                   :rules="rules" label-position="left"
                   label-width="80px">
            <el-form-item label="用户名：" prop="account">
              <el-input v-model="loginForm.account" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input type="password"
                        v-model="loginForm.password"
                        placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <div class="form-item-container">
                <el-input v-model="loginForm.code"
                          maxlength="4"
                          minlength="4"
                          placeholder="验证码"
                          style="width: 90px;">
                </el-input>
                <img :src="codeUrl"
                     style="cursor: pointer; margin-left: 10px;"
                     @click="getCaptcha()"
                     title="看不清点击刷新"/>
              </div>
            </el-form-item>
            <div class="login-btn-container">
              <el-button style="width: 150px;" type="primary"
                         @click="userLogin"
                         :disabled="isButtonDisabled"
                         icon="el-icon-user-solid">登录
              </el-button>
            </div>
          </el-form>
        </el-card>

      </el-tab-pane>



      <el-tab-pane class="container" label="手机号登录" name="telephone">
        <el-card class="card">
          <h2 class="title">手机号登录</h2>
          <el-form ref="refSmsForm" :model="smsForm"
                   class="login-form" :rules="rulesPhone"
                   label-position="left"
                   label-width="80px">
            <el-form-item label="手机号：" prop="telephone">
              <el-input v-model="smsForm.telephone"
                        placeholder="请输入手机号">
                <template #suffix>
                  <el-icon><Iphone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <div class="form-item-container">
                <el-input v-model="smsForm.code" maxlength="4"
                          minlength="4" placeholder="验证码"
                          style="width: 90px; margin-right: 10px;">
                </el-input>
                <el-button type="text" :disabled="smsDisabled"
                           @click="sendSms">
                  <el-icon :size="20"><Message /></el-icon>
                  {{smsText }}
                </el-button>
              </div>
            </el-form-item>
            <div class="login-btn-container">
              <el-button style="width: 150px;"
                         type="primary" @click="smsLogin"
                         icon="el-icon-user-solid">登录
              </el-button>
            </div>
          </el-form>
        </el-card>
      </el-tab-pane>



    </el-tabs>


  </div>
</template>

<style scoped>
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  left: 0;
  background-image: linear-gradient(0, rgb(68, 68, 235), lightblue);
  display: flex;
  /* 水平居中对齐 */
  justify-content: center;
  /* 垂直居中对齐 */
  height: 100%;
}

.card {
  margin-top: 20px;
  width: 450px;
  height: 430px;
  padding: 15px;
}

.title {
  margin-top: 10px;
  font-size: 25px;
  text-shadow: 2px 2px 4px #888;
  text-align: center;
}

.login-form {
  max-width: 300px;
  margin: 0 auto;
}

.login-btn-container {
  text-align: center;
  margin-bottom: 30px;
}

.form-item-container {
  display: flex;
  align-items: flex-end;
}
</style>
